import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { regionData, codeToText } from 'element-china-area-data'
import { useOrderStore } from '@/stores/orderStore'
import { useUserStore } from '@/stores/userStore'
import { addAddress, updateAddress, deleteAddress } from '@/apis/order'

export function useAddress() {
  const userStore = useUserStore()
  const orderStore = useOrderStore()
  const dialogVisible = ref(false)
  const dialogTitle = ref('新增地址')
  const addressForm = ref({})
  const addressFormRef = ref(null)

  // 表单验证规则
  const rules = {
    recipientName: [
      { required: true, message: '请输入收货人姓名', trigger: 'blur' }
    ],
    phoneNumber: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    region: [
      { required: true, message: '请选择所在地区', trigger: 'blur' }
    ],
    streetAddress: [
      { required: true, message: '请输入详细地址', trigger: 'blur' }
    ]
  }

  // 新增地址弹窗
  const showAddressDialog = () => {
    dialogTitle.value = '新增地址'
    addressForm.value = {
      userId: userStore.userInfo.userId,
      isDefault: false
    }
    dialogVisible.value = true
  }

  // 编辑地址
  const editAddress = (address) => {
    dialogTitle.value = '编辑地址'
    // 根据地址信息找到对应的地区编码
    const provinceCode = Object.keys(codeToText).find(key => codeToText[key] === address.province)
    const cityCode = Object.keys(codeToText).find(key => codeToText[key] === address.city)
    const districtCode = Object.keys(codeToText).find(key => codeToText[key] === address.district)

    addressForm.value = {
      ...address,
      region: [provinceCode, cityCode, districtCode]
    }
    dialogVisible.value = true
  }

  // 取消
  const back = () => {
    addressForm.value = {}
    dialogVisible.value = false
    // 重置表单验证状态
    addressFormRef.value?.resetFields()
  }

  // 保存地址
  const saveAddress = async () => {
    if (!addressFormRef.value) return
    try {
      await addressFormRef.value.validate()
      const [provinceCode, cityCode, districtCode] = addressForm.value.region
      const addressData = {
        ...addressForm.value,
        province: codeToText[provinceCode],
        city: codeToText[cityCode],
        district: codeToText[districtCode],
        userId: userStore.userInfo.userId
      }
      delete addressData.region

      const res = addressData.id 
        ? await updateAddress(addressData)
        : await addAddress(addressData)

      if (res.code === '0') {
        ElMessage.success(addressData.id ? '修改成功' : '添加成功')
        dialogVisible.value = false
        orderStore.getAddresses()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.error('保存地址失败:', error)
    }
  }

  // 删除地址
  const handleDeleteAddress = async (id) => {
    try {
      await ElMessageBox.confirm('确认删除该地址吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      const res = await deleteAddress(id)
      if (res.code === '0') {
        ElMessage.success('删除成功')
        orderStore.getAddresses()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  return {
    dialogVisible,
    dialogTitle,
    addressForm,
    addressFormRef,
    rules,
    showAddressDialog,
    editAddress,
    back,
    saveAddress,
    handleDeleteAddress
  }
} 